package com.example.emos.workflow;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class Demo_6 {
    //启动工作流程
    @Resource
    private RuntimeService runtimeService;

    //查找关于自己的任务
    @Resource
    private TaskService taskService;

    //查找历史记录
    @Resource
    private HistoryService historyService;

    @Test
    public void test_1() {
        //设置工作流参数
        HashMap param = new HashMap() {{
            put("empId", "9527"); //申请人
            put("managerId", "9528"); //审批人
            put("reason", "申请10天年假");
        }};
        runtimeService.startProcessInstanceByKey("Process_1716385690962", param);
    }

    @Test
    public void test_2() {
        //以9527查找跟自己有关的工作流任务
        List<Task> list = taskService.createTaskQuery().includeProcessVariables().includeTaskLocalVariables()
                .taskAssignee("9527").orderByTaskCreateTime().desc().list();
        list.forEach(task -> {
            //TODO 员工上传请假单
            taskService.complete(task.getId()); //执行任务
            System.out.println("员工任务执行完毕");
        });
    }

    @Test
    public void test_3() {
        //以9528查找跟自己有关的工作流任务
        List<Task> list = taskService.createTaskQuery().includeProcessVariables().includeTaskLocalVariables()
                .taskAssignee("9528").orderByTaskCreateTime().desc().list();
        list.forEach(task -> {
            Map<String, Object> map = new HashMap<>() {{
                put("result", "同意");
            }};
            //设置全局变量
            taskService.setVariables(task.getId(), map);
            taskService.complete(task.getId());
            System.out.println("经理任务执行完毕");
        });
    }

    @Test
    public void test_4() {
        //以9527查找跟自己有关的已经执行完成的工作流
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .includeTaskLocalVariables().includeProcessVariables().taskAssignee("9527").processFinished()
                .orderByTaskCreateTime().desc().list();
        HistoricTaskInstance historicTaskInstance = list.get(0);
        Map<String, Object> variables = historicTaskInstance.getProcessVariables();
        System.out.println(variables.get("result"));
    }
}
